package com.vm.osm.business.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.JsonObject;
import com.vm.osm.business.dao.*;
import com.vm.osm.business.dto.CreateNotifyReq;
import com.vm.osm.business.dto.app.rsp.AppOrderInfo;
import com.vm.osm.business.dto.app.rsp.AppProblemBase;
import com.vm.osm.business.dto.app.rsp.RspAppOrderPage;
import com.vm.osm.business.dto.app.rsp.RspProblemPage;
import com.vm.osm.business.dto.req.orderInst.ReqModifyTime;
import com.vm.osm.business.dto.rsp.RspPage;
import com.vm.osm.business.dto.rsp.orderInst.AppOrderList;
import com.vm.osm.business.entity.OsmOrderFailure;
import com.vm.osm.business.entity.OsmOrderFlow;
import com.vm.osm.business.service.IAppOrderService;
import com.vm.osm.business.util.*;
import com.vma.eams.spring.boot.log.LogCollector;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenzui on 2018/4/12.
 */
@Service
public class AppOrderServiceImpl implements IAppOrderService {

    @Autowired
    private AppOrderMapper appOrderMapper;

    @Autowired
    private OsmProblemBaseMapper osmProblemBaseMapper;

    @Autowired
    private OsmOrderFailureMapper osmOrderFailureMapper;

    @Autowired
    private OsmOrderFlowMapper osmOrderFlowMapper;

    @Autowired
    private OsmCheckPlanInstMapper checkPlanInstMapper;

    @Autowired
    private NotifyUtil notifyUtil;


    @Override
    public RspAppOrderPage findPage(String staffId,Integer pageNum,Integer pageSize,String enterpriseId) {

        // TODO: 2018/4/14 查询数据权限，返回部门ID列表
        RspAppOrderPage rspAppOrderPage = new RspAppOrderPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<AppOrderInfo> dataList = appOrderMapper.selectOrders(staffId,enterpriseId);
        rspAppOrderPage.setData_list(dataList);
        rspAppOrderPage.setTotal_num(page.getTotal());
        rspAppOrderPage.setPage_num(page.getPageNum());
        rspAppOrderPage.setPage_size(page.getPageSize());
        return rspAppOrderPage;
    }

    @Override
    public RspProblemPage findPage(String enterpriseId, String failTypeId, String title, Integer pageNum, Integer pageSize) {

        RspProblemPage rspProblemPage = new RspProblemPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<AppProblemBase> dataList = osmProblemBaseMapper.selectByCondition(title,failTypeId);
        rspProblemPage.setData_list(dataList);
        rspProblemPage.setTotal_num(page.getTotal());
        rspProblemPage.setPage_num(page.getPageNum());
        rspProblemPage.setPage_size(page.getPageSize());
        return rspProblemPage;
    }

    @Override
    public Map<Integer, Integer> data(String staffId) {
        Date today = new Date();
        String startDay = DateFormatUtils.formate(today,DateFormatUtils.SPLIT_PATTERN_DATE)+" 00:00:00";
        String endDay = DateFormatUtils.formate(today,DateFormatUtils.SPLIT_PATTERN_DATE)+" 23:59:59";
        //查询今日完成
        int typeFailureComplete = appOrderMapper.getFailNumber(staffId,"8",startDay,endDay);
        int typeLoopComplete = appOrderMapper.getLoopNumber(staffId,"8",startDay,endDay);
        //查询今日接单
        int typeFailureAccept = appOrderMapper.getFailNumber(staffId,"6",startDay,endDay);
        int typeLoopAccept = appOrderMapper.getLoopNumber(staffId,"6",startDay,endDay);

        //查询本月完成
        String startMonth = DateFormatUtils.formate(today,"yyyy-MM")+"-01 00:00:00";
        String endMonth = DateFormatUtils.formate(today,"yyyy-MM")+"-31 23:59:59";
        int typeFailureMonthComplete = appOrderMapper.getFailNumber(staffId,"8",startMonth,endMonth);
        int typeLoopMonthComplete = appOrderMapper.getLoopNumber(staffId,"8",startMonth,endMonth);

        Map<Integer,Integer> result = new HashMap<>();
        result.put(1,typeFailureComplete+typeLoopComplete);
        result.put(2,typeFailureAccept+typeLoopAccept);
        result.put(3,typeFailureMonthComplete+typeLoopMonthComplete);
        return result;
    }

    @Override
    public void confirm(HttpServletRequest request,String orderId) {
        OsmOrderFailure orderFailure = osmOrderFailureMapper.selectByPrimaryKey(orderId);

        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setOperateUserName(UserDataUtil.getStaffName(request));
        flow.setOperateUserId(UserDataUtil.getStaffId(request));
        flow.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
        flow.setStatus(new Byte("1"));
        flow.setOrderId(orderId);
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setSimpleDesc("确认工单完成");
        orderFailure.setStatus("8");
        osmOrderFlowMapper.insertSelective(flow);
        osmOrderFailureMapper.updateByPrimaryKeySelective(orderFailure);
        String staffId = orderFailure.getAcceptStaffId();
        String enterpriseId = orderFailure.getEnterpriseId();

        if(orderFailure.getIsFromOut() != null && orderFailure.getIsFromOut().equals(1)){
            OsmOrderFailure old = osmOrderFailureMapper.selectByPrimaryKey(orderFailure.getOutOrderId());
            old.setStatus("14");
            osmOrderFailureMapper.updateByPrimaryKeySelective(old);
            OsmOrderFlow flow2 = new OsmOrderFlow();
            flow.setOperateUserName(UserDataUtil.getStaffName(request));
            flow.setOperateUserId(UserDataUtil.getStaffId(request));
            flow.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
            flow.setStatus(new Byte("1"));
            flow.setOrderId(old.getId());
            flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
            flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
            flow.setId(UuidUtil.getRandomUuid());
            flow.setSimpleDesc("确认工单完成");
            orderFailure.setStatus("8");
            osmOrderFlowMapper.insertSelective(flow2);

            staffId= old.getAcceptStaffId();
            enterpriseId = old.getEnterpriseId();
        }

        String content = "您处理的工单【"+orderFailure.getOrderTitle() +"】已确认";
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("order_type","1");
        jsonObject.addProperty("type","1");
        jsonObject.addProperty("order_id",orderFailure.getId());
        String extra = GsonUtil.toJson(jsonObject);
        String title = "收到派单";
        String sender = UserDataUtil.getStaffId(request);
        String target = staffId;
        CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,sender,target,enterpriseId);

        notifyUtil.send(createNotifyReq);

        LogCollector.INSTANCE.put("故障",orderFailure.getOrderNbr());
    }
    @Transactional
    @Override
    public void again(HttpServletRequest request, String orderId,String remark) {
        OsmOrderFailure orderFailure = osmOrderFailureMapper.selectByPrimaryKey(orderId);
        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setOperateUserName(UserDataUtil.getStaffName(request));
        flow.setOperateUserId(UserDataUtil.getStaffId(request));
        flow.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
        flow.setStatus(new Byte("1"));
        flow.setOrderId(orderId);
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setSimpleDesc("退回工单:"+remark);
        orderFailure.setStatus("14");
        osmOrderFlowMapper.insertSelective(flow);


        OsmOrderFailure old = osmOrderFailureMapper.queryOutOrderByNbr(orderFailure.getOrderNbr());
        if(old != null){
            orderFailure.setStatus("17");
            osmOrderFailureMapper.updateByPrimaryKeySelective(orderFailure);

            old.setStatus("14");
            osmOrderFailureMapper.updateByPrimaryKeySelective(old);
            OsmOrderFlow flow2 = new OsmOrderFlow();
            flow2.setOperateUserName(UserDataUtil.getStaffName(request));
            flow2.setOperateUserId(UserDataUtil.getStaffId(request));
            flow2.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
            flow2.setStatus(new Byte("1"));
            flow2.setOrderId(old.getId());
            flow2.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
            flow2.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
            flow2.setId(UuidUtil.getRandomUuid());
            flow2.setSimpleDesc("退回工单:"+remark);
            orderFailure.setStatus("14");
            osmOrderFlowMapper.insertSelective(flow2);


            String content = "您处理的工单【"+old.getOrderTitle() +"】被退回，请重新处理";
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("order_type","1");
            jsonObject.addProperty("type","1");
            jsonObject.addProperty("order_id",old.getId());
            String extra = GsonUtil.toJson(jsonObject);
            String title = "收到派单";
            String sender = UserDataUtil.getStaffId(request);
            String target = orderFailure.getAcceptStaffId();
            CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,sender,target,orderFailure.getEnterpriseId());
            notifyUtil.send(createNotifyReq);
        }else {
            osmOrderFailureMapper.updateByPrimaryKeySelective(orderFailure);

            String content = "您处理的工单【"+orderFailure.getOrderTitle() +"】被退回，请重新处理";
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("order_type","1");
            jsonObject.addProperty("type","1");
            jsonObject.addProperty("order_id",orderFailure.getId());
            String extra = GsonUtil.toJson(jsonObject);
            String title = "收到派单";
            String sender = UserDataUtil.getStaffId(request);
            String target = orderFailure.getAcceptStaffId();
            CreateNotifyReq createNotifyReq = new CreateNotifyReq(content,extra,title,sender,target,orderFailure.getEnterpriseId());
            notifyUtil.send(createNotifyReq);
        }


        LogCollector.INSTANCE.put("故障",orderFailure.getOrderNbr());

    }

    @Override
    public void cancel(HttpServletRequest request, String orderId) {
        OsmOrderFailure orderFailure = osmOrderFailureMapper.selectByPrimaryKey(orderId);
        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setOperateUserName(UserDataUtil.getStaffName(request));
        flow.setOperateUserId(UserDataUtil.getStaffId(request));
        flow.setStatus(new Byte("1"));
        flow.setOrderId(orderId);
        flow.setOperateUserIcon(UserDataUtil.getStaffHeadImg(request));
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setSimpleDesc("撤销工单");
        orderFailure.setStatus("9");
        osmOrderFlowMapper.insertSelective(flow);
        osmOrderFailureMapper.updateByPrimaryKeySelective(orderFailure);
    }

    @Override
    public Map queryStatus(String staffId) {
        List<Map<String,Long>> loop = checkPlanInstMapper.queryStatus(staffId);

        List<Map<String,Long>> fail = osmOrderFailureMapper.queryStatus(staffId);

        Map<String,Long> result = new HashMap();

        result.put("5",loop.get(0).get("num")+fail.get(0).get("num"));
        result.put("6",loop.get(1).get("num")+fail.get(1).get("num"));
        result.put("7",loop.get(2).get("num")+fail.get(2).get("num"));
        result.put("8",loop.get(3).get("num")+fail.get(3).get("num"));
        result.put("14",loop.get(4).get("num")+fail.get(4).get("num"));
        result.put("15",loop.get(5).get("num")+fail.get(5).get("num"));

        result.put("4",checkPlanInstMapper.queryCatch(staffId)+osmOrderFailureMapper.queryCatch(staffId));

        return result;
    }
    public Map queryStatusByDept(String departmentId,String enterpriseId) {
        List<Map<String,Long>> loop = checkPlanInstMapper.queryStatusByDept(departmentId,enterpriseId);

        List<Map<String,Long>> fail = osmOrderFailureMapper.queryStatusByDept(departmentId,enterpriseId);

        Map<String,Long> result = new HashMap();
        result.put("4",loop.get(0).get("num")+fail.get(0).get("num"));
        result.put("5",loop.get(1).get("num")+fail.get(1).get("num"));
        result.put("6",loop.get(2).get("num")+fail.get(2).get("num"));
        result.put("7",loop.get(3).get("num")+fail.get(3).get("num"));
        result.put("8",loop.get(4).get("num")+fail.get(4).get("num"));
        result.put("12",loop.get(5).get("num")+fail.get(5).get("num"));
        result.put("15",loop.get(6).get("num")+fail.get(6).get("num"));


        return result;
    }

    @Override
    @Transactional
    public void turnBack(HttpServletRequest request, String orderId, String remark) {
        // TODO: 2018/4/26 校验订单状态
        OsmOrderFailure orderFailure = osmOrderFailureMapper.selectByPrimaryKey(orderId);

        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setOperateUserName(UserDataUtil.getStaffName(request));
        flow.setOperateUserId(UserDataUtil.getStaffId(request));
        flow.setStatus(new Byte("1"));
        flow.setOrderId(orderId);
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setSimpleDesc("撤回上报订单");
        orderFailure.setStatus("11");//上报中
        osmOrderFlowMapper.insertSelective(flow);
        osmOrderFailureMapper.updateByPrimaryKeySelective(orderFailure);

        OsmOrderFailure out =  osmOrderFailureMapper.selectByOutId(orderId);
        out.setStatus("9");
        out.setModifyTime(new Date());
        osmOrderFailureMapper.updateByPrimaryKeySelective(out);
        LogCollector.INSTANCE.put("故障",orderFailure.getOrderNbr());


    }

    @Override
    public RspPage<AppOrderList> queryAppMyOrder(String staffId, String enterpriseId, String type,Integer pageNum,Integer pageSize) {
        RspPage<AppOrderList> rspPage = new RspPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<AppOrderList> dataList = osmOrderFailureMapper.queryAppMyOrder(staffId,enterpriseId,type);
        rspPage.setData_list(dataList);
        rspPage.setTotal_num(page.getTotal());
        rspPage.setPage_num(page.getPageNum());
        rspPage.setPage_size(page.getPageSize());
        return rspPage;
    }

    @Override
    public RspPage<AppOrderList> queryAppDepartmentOrder(String enterpriseId, String type, Integer pageNum, Integer pageSize) {
        RspPage<AppOrderList> rspPage = new RspPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        String[] status=null;
        if(type != null && !"".equals(type)){
            status = type.split(",");
        }
        List<AppOrderList> dataList = osmOrderFailureMapper.queryAppDepartmentOrder(enterpriseId,status);
        rspPage.setData_list(dataList);
        rspPage.setTotal_num(page.getTotal());
        rspPage.setPage_num(page.getPageNum());
        rspPage.setPage_size(page.getPageSize());
        return rspPage;
    }

    @Override
    public void modifyTime(ReqModifyTime reqModifyTime,HttpServletRequest request) {

        String orderId = reqModifyTime.getOrder_id();
        OsmOrderFailure orderFailure = osmOrderFailureMapper.selectByPrimaryKey(reqModifyTime.getOrder_id());

        OsmOrderFlow flow = new OsmOrderFlow();
        flow.setOperateUserName(UserDataUtil.getStaffName(request));
        flow.setOperateUserId(UserDataUtil.getStaffId(request));
        flow.setStatus(new Byte("1"));
        flow.setOrderId(orderId);
        flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
        flow.setId(UuidUtil.getRandomUuid());
        flow.setSimpleDesc("改预约时间:"+(orderFailure.getAppointmentTime()!=null?(DateFormatUtils.formate(orderFailure.getAppointmentTime())+"--"+DateFormatUtils.formate(reqModifyTime.getAppointment_time())):DateFormatUtils.formate(reqModifyTime.getAppointment_time()))+"\n"+reqModifyTime.getRemark());
        osmOrderFlowMapper.insertSelective(flow);

        orderFailure.setAppointmentTime(reqModifyTime.getAppointment_time());
        osmOrderFailureMapper.updateByPrimaryKeySelective(orderFailure);

    }

    public static void main(String[] args){
        Date date = new Date();
//        String startMonth = DateFormatUtils.formate(date,DateFormatUtils.SPLIT_PATTERN_MONTH)+"-01 00:00:00";
//        String endMonth = DateFormatUtils.formate(date,DateFormatUtils.SPLIT_PATTERN_MONTH)+"-31 23:59:59";
//        String start = DateFormatUtils.formate(date,DateFormatUtils.SPLIT_PATTERN_DATE)+" 00:00:00";
//        String end = DateFormatUtils.formate(date,DateFormatUtils.SPLIT_PATTERN_DATE)+" 23:59:59";
//        System.out.println(startMonth+"----"+endMonth);
        String[] status = "".split(",");
        for(int i=0;i<status.length;i++){
            System.out.println(status[i]);

        }

    }
}
